﻿using System;
using System.Text;
using System.Net;
using System.Xml.Linq;

namespace iTunesPlaycountUpdater
{
    static class LastFmApi
    {
        private static readonly string requestUrlBase = @"http://ws.audioscrobbler.com/2.0/?method=library.gettracks&api_key={0}&user={1}&page={2}";

        public static XElement GetTracks(string apiKey, string userName, int page)
        {
            int pages = 0;
            return GetTracks(apiKey, userName, page, out pages);
        }
        public static XElement GetTracks(string apiKey, string userName, int page, out int pageCount)
        {
            using (WebClient client = new WebClient())
            {
                byte[] data = client.DownloadData(string.Format(requestUrlBase, apiKey, userName, page));//+ @"&artist=The White Stripes");
                XElement response = XElement.Parse(Encoding.UTF8.GetString(data));
                if (response.Attribute("status").Value == "ok")
                {
                    XElement tracks = response.Element("tracks");
                    pageCount = int.Parse(tracks.Attribute("totalPages").Value);
                    return tracks;
                }

                pageCount = 0;
                return null; // failed, so no response
            }
        }
    }
}
